
package com.wind.cloud.commonservice.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wind.cloud.common.constant.CommonConstant;
import com.wind.cloud.common.constant.MqQueueConstant;
import com.wind.cloud.common.vo.ZuulRoute;
import com.wind.cloud.commonservice.entity.SysZuulRoute;
import com.wind.cloud.commonservice.mapper.SysZuulRouteMapper;
import com.wind.cloud.commonservice.service.SysZuulRouteService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


/**
 * <p>
 * 动态路由配置表 服务实现类
 * </p>
 *
 * @author lengleng
 * @since 2018-05-15
 */
@Service
public class SysZuulRouteServiceImpl extends ServiceImpl<SysZuulRouteMapper, SysZuulRoute> implements SysZuulRouteService {

    @Resource
    private RedisTemplate<String, List<ZuulRoute>> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 立即生效配置
     *
     * @return
     */
    @Override
    public Boolean applyZuulRoute() {
        redisTemplate.boundValueOps(CommonConstant.ROUTE_KEY).set(listAll());
        // TODO 发布路由变更事件？
        rabbitTemplate.convertAndSend(MqQueueConstant.ROUTE_CONFIG_CHANGE, 1);
        return Boolean.TRUE;
    }

    @Override
    public List<ZuulRoute> listAll() {
        QueryWrapper<SysZuulRoute> wrapper = new QueryWrapper<>();
        wrapper.eq(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        List<SysZuulRoute> sysZuulRoutes = list(wrapper);

        List<ZuulRoute> zuulRoutes = new ArrayList<>(sysZuulRoutes.size());
        for (SysZuulRoute sysZuulRoute : sysZuulRoutes) {
            if (StringUtils.isEmpty(sysZuulRoute.getPath())) {
                continue;
            }
            ZuulRoute zuulRoute = new ZuulRoute();
            zuulRoute.setPath(sysZuulRoute.getPath());
            zuulRoute.setServiceId(sysZuulRoute.getServiceId());
            zuulRoute.setRetryable(sysZuulRoute.getRetryable() == null ? Boolean.FALSE : sysZuulRoute.getRetryable() == 1);
            zuulRoute.setStripPrefix(sysZuulRoute.getStripPrefix() == null ? Boolean.TRUE : sysZuulRoute.getStripPrefix() == 1);
            Set<String> sensitiveHeaders = StringUtils.commaDelimitedListToSet(sysZuulRoute.getSensitiveheadersList());
            zuulRoute.setSensitiveHeaders(sensitiveHeaders);
            zuulRoutes.add(zuulRoute);
        }
        return zuulRoutes;
    }
}
